import Fly from 'flyio/dist/npm/wx'
import $ from '@/common/base.js'
import Config from '@/settings.js'
import qs from 'qs'

const request = new Fly()

// request配置
request.config.baseURL = Config.baseUrl
request.config.timeout = 30000		//10s

request.interceptors.request.use((request) => {
	request.headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
	request.headers['Content-type'] = 'application/json'
	const token = $.getStore('token')
	if (token) {
		request.headers['token'] = token
	}
	return request
})

request.interceptors.response.use((response, promise) => {
	$.done()
	const res = response.data
	let code=Number(res.code)
	switch (code) {
		case 201:
			$.toast(res.msg, 'fail');
			return promise.reject()
		case 416:
			uni.showToast({
				title: '登录信息过期！',
				icon: 'none'
			})
			$.removeStore('userInfo')
			$.removeStore('token')
			setTimeout(() => {
				uni.navigateTo({
						url: `/pages/login/login`
				})
			}, 2000)
			break;
		case 408:
			console.log('408408408');
			uni.showToast({
				title: '登录超时,请重新登录!',
				icon: 'none'
			})
			$.removeStore('userInfo')
			$.removeStore('token')
			setTimeout(() => {
				uni.navigateTo({
						url: `/pages/login/login`
				})
			}, 2000)
			break;
		case 10001:
			return promise.reject(res)
		case 10008:
			return promise.reject(res)
	}
	return promise.resolve(res.data || res)
}, (err, promise) => {
	let res = err.response && err.response.data
	let page = $.getCurrentPage()
	switch (err.status) {
		case 400:
			$.error(res.msg);
			break;
		case 401:	//用户未登录 
			let page = $.getCurrentPage()
			$.done()
			uni.navigateTo({
					url: `/pages/login/login`
			})
			break;
			
		default:
			$.error('接口请求失败')
	}
})

export default request
